package com.milo.xstream.xml;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.Serializable;
import java.util.Map;

/**
 * 支付宝生活号推送过来的xml消息
 * @author milogenius
 * @date 2020/4/3 15:29
 *
 */
@Data
@Slf4j
@XStreamAlias("XML")
public class AlipayXmlMessage implements Serializable {
  private static final long serialVersionUID = -3586245291677274914L;

  /**
   * 使用dom4j解析的存放所有xml属性和值的map.
   */
  private Map<String, Object> allFieldsMap;

  ///////////////////////
  // 以下都是支付宝生活号推送过来的消息的xml的element所对应的属性
  ///////////////////////

  /**AppId*/
  @XStreamAlias("AppId")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String appId;


  /**用户userid,用户唯一标识*/
  @XStreamAlias("FromAlipayUserId")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String fromAlipayUserId;


  /**消息创建时间*/
  @XStreamAlias("CreateTime")
  private Long createTime;

  /**消息类型*/
  @XStreamAlias("MsgType")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String msgType;


  /**事件类型*/
  @XStreamAlias("EventType")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String eventType;

  /**用户从特定场景关注,带的自定义参数值*/
  @XStreamAlias("ActionParam")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String actionParam;

  /**支付宝用户信息*/
  @XStreamAlias("UserInfo")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String userInfo;

  /**消息id 用于消息去重*/
  @XStreamAlias("MsgId")
  private String msgId;




  public static AlipayXmlMessage fromXml(String xml) {
    //修改微信变态的消息内容格式，方便解析
    xml = xml.replace("<?xml version=\\\"1.0\\\" encoding=\\\"gbk\\\"?>", "");
    final AlipayXmlMessage xmlMessage = XStreamTransformer.fromXml(AlipayXmlMessage.class, xml);
    xmlMessage.setAllFieldsMap(XmlUtils.xml2Map(xml));
    return xmlMessage;
  }

  public static AlipayXmlMessage fromXml(InputStream is) {
    return XStreamTransformer.fromXml(AlipayXmlMessage.class, is);
  }



}
